package com.kis.bot.utils.api

import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import com.kis.bot.enums.StringEnums
import com.kis.bot.model.WeChat
import org.apache.http.util.EntityUtils
import java.awt.Desktop
import java.io.File
import java.io.FileOutputStream
import java.util.*

/**
 * Created by wongloong on 16-9-2.
 */
object Tools {
    fun getUUID(): String {
        val params = hashMapOf<String, String>("appid" to StringEnums.APPID.value,
                "fun" to "new", "lang" to "zh_CN")
        val response = Http.post(StringEnums.GETUUIDURL.value, params)
        if (null != response.entity) {
            val body = EntityUtils.toString(response.entity)
            val uuid = body.split("\"")[1]
            return uuid
        }
        response.close()
        return ""
    }

    fun createQrCode(wx: WeChat) {
        wx.uuid = getUUID()
        val url = StringEnums.SCANURL.value + "/" + wx.uuid
        val params = hashMapOf("t" to "webwx", "_" to Date().time.toString(),
                "lang" to "zh_CN")
        val response = Http.post(url, params)
        if (null != response.entity) {
            val qrCode = File("${System.getProperty("user.dir")}/qr.jpeg")
            var output = FileOutputStream(qrCode)
            output.write(response.entity.content.readBytes())
            var f = File("${System.getProperty("user.dir")}/qr.jpeg")
            Desktop.getDesktop().open(f)
        }
        response.close()
    }

    fun checkLogin(wx: WeChat, tip: Int): String {
        val url = StringEnums.checkState.value + "&uuid=${wx.uuid}&tip=${tip}"
        val response = Http.get(url)
        val body = EntityUtils.toString(response.entity)
        val code: String = body.split(";")[0].split("=")[1]
        when (code) {
            "200" -> {
                wx.redirectUri = body.split(";")[1].split("window.redirect_uri=")[1].replace("\"", "")
                wx.baseUri = wx.redirectUri.split("/webwxnew")[0]
            }
        }
        response.close()
        return code
    }

    fun login(wx: WeChat): Boolean {
        val url = wx.redirectUri + "&fun=new"
        val response = Http.get(url)
        val dom = EntityUtils.toString(response.entity)
        wx.sKey = dom.getDomValue("skey")
        wx.uin = dom.getDomValue("wxuin")
        wx.sid = dom.getDomValue("wxsid")
        wx.pass_ticket = dom.getDomValue("pass_ticket")
        if (wx.sKey.isNullOrEmpty() || wx.uin.isNullOrEmpty() ||
                wx.sid.isNullOrEmpty() || wx.pass_ticket.isNullOrEmpty()) {
            return false
        }
        wx.deviceId = "e".getDeviceId().toString()
        wx.baseRequest = JSONObject()
        wx.baseRequest.put("Uin", wx.uin)
        wx.baseRequest.put("Skey", wx.sKey)
        wx.baseRequest.put("Sid", wx.sid)
        wx.baseRequest.put("DeviceId", wx.deviceId)
        response.close()
        return true
    }

    fun initWx(wx: WeChat): Boolean {
        var result = false
        var url = wx.baseUri + "/webwxinit?r=${Date().getShortTime()}&pass_ticket=${wx.pass_ticket}&skey=${wx.sKey}"
        val json = JSONObject()
        json.put("BaseRequest", wx.baseRequest)
        val response = Http.post(url, json)
        val body = EntityUtils.toString(response.entity, "utf8")
        val obj: JSONObject = JSON.parse(body) as JSONObject
        val baseResponse = obj.getJSONObject("BaseResponse")
        val ret = baseResponse?.getIntValue("Ret") ?: -1
        if (ret == 0) {
            val syncKeyObj = obj.getJSONObject("SyncKey")
            wx.user = obj.getJSONObject("User")
            val synckey = StringBuffer()

            val list = syncKeyObj.getJSONArray("List")
            var i = 0
            val len = list.size
            while (i < len) {
                val item = list.getJSONObject(i)
                synckey.append("|" + item.getIntValue("Key") + "_" + item.getIntValue("Val"))
                i++
            }
            wx.syncKey = synckey.substring(1)
            result = true
        }
        response.close()
        return result
    }

    fun webwxstatusnotify(wx: WeChat): Boolean {
        val url = wx.baseUri + "/webwxstatusnotify?lang=zh_CN&pass_ticket=" + wx.pass_ticket
        val param = JSONObject()
        param.put("BaseRequest", wx.baseRequest)
        param.put("Code", 3)
        param.put("FromUserName", wx.user.get("UserName"))
        param.put("ToUserName", wx.user.get("UserName"))
        param.put("ClientMsgId", Date().time)
        val response = Http.post(url, param)
        val obj = JSON.parse(EntityUtils.toString(response.entity)) as JSONObject
        response.close()
        if (obj.getJSONObject("BaseResponse")?.getIntValue("Ret") == 0) return true
        return false
    }
    fun getContact(wx: WeChat){
        var url = "${wx.baseUri}/webwxgetcontact?pass_ticket=${wx.pass_ticket}&skey=${wx.sKey}&r=${Date().time}"
        val param = JSONObject()
        param.put("BaseRequest", wx.baseRequest)
        val response = Http.post(url,param)
        val body = response.entity
        val obj = JSON.parse(EntityUtils.toString(body,"utf8")) as JSONObject
        if(obj.getIntValue("Ret")==0){
            wx.memberList=obj.getJSONArray("MemberList")
            val chatList = JSONArray()
            val contactList = JSONArray()
            for(member in wx.memberList){
                member as JSONObject
                if(member.getString("UserName").startsWith("@")&&(member.getIntValue("VerifyFlag") and 8==0)){
                    contactList.add(member)
                }
            }
            wx.contactList=contactList
            wx.chatroomList=chatList
        }
    }
    fun getChat(wx: WeChat){
        var url = "${wx.baseUri}/webwxbatchgetcontact"
        val params = hashMapOf("type" to "ex","pass_ticket" to wx.pass_ticket,"r" to Date().time.toString())
        val response = Http.post(url,params)
        val body = response.entity
        val obj = JSON.parse(EntityUtils.toString(body,"utf8")) as JSONObject
        if(obj.getIntValue("Ret")==0){
            wx.chatroomList=obj.getJSONArray("List")?: JSONArray()
            val chatList = JSONArray()
            val contactList = JSONArray()
            for(member in wx.chatroomList){
                member as JSONObject
                if(member.getString("UserName").startsWith("@@")){
                    contactList.add(member)
                }
            }
            wx.contactList=contactList
            wx.chatroomList=chatList
        }
    }
}